package com.daervin.svc.manager;

import com.daervin.svc.common.exception.CommonException;
import com.daervin.svc.common.exception.ErrorCode;
import com.daervin.svc.common.utils.PathUtils;
import org.imgscalr.Scalr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * Created by daervin on 2023/8/23
 */
@Component
public class ImageManger {
    @Value("${upload.path}")
    private String filePath;

    public String upload(MultipartFile image) {
        if (image.isEmpty()) {
            throw new CommonException(ErrorCode.ERROR_PARAM, "图片不存在");
        }

        try {
            // 获取图片文件名
            String originalFilename = image.getOriginalFilename();
            String fileName = PathUtils.generateFilePath(originalFilename);

            // 创建czs目录
            File czsDirectory = new File(filePath);
            if (!czsDirectory.exists()) {
                czsDirectory.mkdirs();
            }

            // 构建文件路径
            String finalFilePath = filePath + File.separator + fileName;

            File outputFile = new File(finalFilePath); // 输出压缩后的图片文件

            // 读取输入图像
            BufferedImage inputImage = ImageIO.read(image.getInputStream());
            int targetWidth = 200;
            int targetHeight = 200;

            // 调整图像大小为目标尺寸
            BufferedImage resizedImage = Scalr.resize(inputImage, Scalr.Method.ULTRA_QUALITY,
                    targetWidth, targetHeight);

            // 将调整后的图像转换为字节数组
            ImageIO.write(resizedImage, "png", outputFile);

            outputFile.setExecutable(false, false);
            outputFile.setWritable(true, true);
            outputFile.setReadable(true, false);

            return finalFilePath;
        } catch (Exception e) {
            throw new CommonException(ErrorCode.SYSTEM_ERROR, "图片解析失败");
        }
    }
}
